"use client";

import { MainContext } from "@/src/providers/MainProvider";
import {
  Box,
  Flex,
  Text,
  Container,
  Heading,
  Divider,
  Button,
  useColorModeValue,
  useToast,
  AlertDialog,
  AlertDialogBody,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogContent,
  AlertDialogOverlay,
  Progress,
  Stack,
  HStack,
  VStack,
  Badge,
} from "@chakra-ui/react";
import { useContext, useState, useRef } from "react";
import { motion } from "framer-motion";

const MotionBox = motion(Box);

function KBDeviceInfo() {
  const mainContext = useContext(MainContext);
  const {
    t,
    deviceVersion,
    connectedKeyboard,
    restoreKeyboardFactorySettings,
  } = mainContext;
  const toast = useToast();

  // 状态
  const [firmwareVersion, setFirmwareVersion] = useState(deviceVersion);
  const [driverVersion, setDriverVersion] = useState("v1.0.0");
  const [isUpgrading, setIsUpgrading] = useState(false);
  const [upgradeProgress, setUpgradeProgress] = useState(0);
  const [showResetDialog, setShowResetDialog] = useState(false);
  const [showUpgradeDialog, setShowUpgradeDialog] = useState(false);

  // 引用
  const cancelRef = useRef<HTMLButtonElement>(null);

  // 功能
  const handleUpgradeFirmware = () => {
    setIsUpgrading(true);
    setUpgradeProgress(0);

    // 模拟升级进度
    const interval = setInterval(() => {
      setUpgradeProgress((prev) => {
        const next = prev + Math.random() * 10;
        if (next >= 100) {
          clearInterval(interval);
          setTimeout(() => {
            setIsUpgrading(false);
            setShowUpgradeDialog(false);
            setFirmwareVersion(
              "v" + (parseFloat(firmwareVersion.substring(1)) + 0.1).toFixed(1)
            );
            toast({
              title: t("760"),
              status: "success",
              duration: 3000,
              isClosable: true,
            });
          }, 500);
          return 100;
        }
        return next;
      });
    }, 150);
  };

  const handleResetDevice = () => {
    setShowResetDialog(false);
    restoreKeyboardFactorySettings(connectedKeyboard);
    toast({
      title: t("761"),
      description: t("762"),
      status: "success",
      duration: 3000,
      isClosable: true,
    });
  };

  const bgColor = useColorModeValue(
    "rgba(255, 255, 255, 0.5)",
    "rgba(20, 20, 20, 0.5)"
  );
  const borderColor = useColorModeValue(
    "rgba(255, 140, 0, 0.2)",
    "rgba(255, 140, 0, 0.3)"
  );
  const accentColor = "rgb(255, 140, 0)";
  const textColor = useColorModeValue("rgb(15, 23, 42)", "white");
  const subTextColor = useColorModeValue("rgb(100, 116, 139)", "gray.400");

  const InfoCard = ({
    icon,
    title,
    children,
  }: {
    icon: React.ReactNode;
    title: string;
    children: React.ReactNode;
  }) => (
    <MotionBox
      bg={bgColor}
      backdropFilter="blur(20px)"
      borderRadius="16px"
      border={`1px solid ${borderColor}`}
      p={6}
      boxShadow="0 8px 32px rgba(255, 140, 0, 0.1)"
      _hover={{
        boxShadow: "0 8px 32px rgba(255, 140, 0, 0.12)",
        transform: "translateY(-2px)",
      }}
      transition={{ property: "all", duration: 0.3, ease: "easeInOut" }}
      style={{
        WebkitBackdropFilter: "blur(20px)",
      }}
    >
      <HStack mb={4} spacing={3}>
        <Box color={accentColor}>{icon}</Box>
        <Heading size="md" color={textColor} fontWeight="600">
          {title}
        </Heading>
      </HStack>
      <Divider mb={4} borderColor="rgba(255, 140, 0, 0.1)" />
      {children}
    </MotionBox>
  );

  return (
    <Box p={8} minH="calc(100vh - 200px)">
      {/* 页面标题 */}
      <MotionBox
        initial={{ opacity: 0, y: -20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
        mb={8}
      >
        <Heading size="lg" color={textColor} fontWeight="600" mb={2}>
          {t("1025")}
        </Heading>
        <Text color={subTextColor} fontSize="md">
          {t("1026")}
        </Text>
      </MotionBox>

      <Stack spacing={6}>
        {/* 设备信息卡片 */}
        <MotionBox
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, delay: 0.1 }}
        >
          <InfoCard
            icon={
              <svg
                width="24"
                height="24"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
              >
                <circle cx="12" cy="12" r="10" />
                <line x1="12" y1="16" x2="12" y2="12" />
                <line x1="12" y1="8" x2="12.01" y2="8" />
              </svg>
            }
            title={t("770")}
          >
            <Stack spacing={4}>
              <Flex justify="space-between" align="center">
                <Text fontWeight="500" color={textColor}>
                  {t("771")}
                </Text>
                <Badge
                  bg="rgba(255, 140, 0, 0.1)"
                  color={accentColor}
                  px={3}
                  py={1}
                  borderRadius="8px"
                  fontWeight="500"
                >
                  {driverVersion}
                </Badge>
              </Flex>
              <Flex justify="space-between" align="center">
                <Text fontWeight="500" color={textColor}>
                  {t("772")}
                </Text>
                <Badge
                  bg="rgba(255, 140, 0, 0.1)"
                  color={accentColor}
                  px={3}
                  py={1}
                  borderRadius="8px"
                  fontWeight="500"
                >
                  {firmwareVersion}
                </Badge>
              </Flex>
              <Flex justify="space-between" align="center">
                <Text fontWeight="500" color={textColor}>
                  {t("775")}
                </Text>
                <HStack>
                  <Box
                    w="8px"
                    h="8px"
                    borderRadius="full"
                    bg="rgb(34, 197, 94)"
                    boxShadow="0 0 8px rgba(34, 197, 94, 0.3)"
                  />
                  <Text color="rgb(34, 197, 94)" fontWeight="500" fontSize="sm">
                    {t("776")}
                  </Text>
                </HStack>
              </Flex>
            </Stack>
          </InfoCard>
        </MotionBox>

        {/* 设备操作卡片 */}
        <MotionBox
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, delay: 0.2 }}
        >
          <InfoCard
            icon={
              <svg
                width="24"
                height="24"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
              >
                <path d="M23 4v6h-6" />
                <path d="M1 20v-6h6" />
                <path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15" />
              </svg>
            }
            title={t("780")}
          >
            <Stack spacing={4}>
              <Box>
                <Text
                  mb={3}
                  color={subTextColor}
                  fontSize="sm"
                  lineHeight="1.5"
                >
                  {t("781")}
                </Text>
                <Button
                  w="100%"
                  leftIcon={
                    <svg
                      width="18"
                      height="18"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2"
                    >
                      <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
                      <polyline points="17 8 12 3 7 8" />
                      <line x1="12" y1="3" x2="12" y2="15" />
                    </svg>
                  }
                  onClick={() => setShowUpgradeDialog(true)}
                  bg={`linear-gradient(135deg, ${accentColor} 0%, ${accentColor} 100%)`}
                  color="white"
                  _hover={{
                    background:
                      "linear-gradient(135deg, rgb(255, 120, 0) 0%, rgb(255, 145, 0) 100%)",
                    transform: "translateY(-1px)",
                    boxShadow: "0 6px 16px rgba(255, 140, 0, 0.4)",
                  }}
                  _active={{
                    bg: "rgb(29, 78, 216)",
                  }}
                  borderRadius="12px"
                  h="48px"
                  fontWeight="500"
                  transition="all 0.2s"
                >
                  {t("782")}
                </Button>
              </Box>

              <Box>
                <Text
                  mb={3}
                  color={subTextColor}
                  fontSize="sm"
                  lineHeight="1.5"
                >
                  {t("783")}
                </Text>
                <Button
                  w="100%"
                  leftIcon={
                    <svg
                      width="18"
                      height="18"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2"
                    >
                      <path d="M23 4v6h-6" />
                      <path d="M1 20v-6h6" />
                      <path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15" />
                    </svg>
                  }
                  onClick={() => setShowResetDialog(true)}
                  variant="outline"
                  borderColor="rgb(239, 68, 68)"
                  color="rgb(239, 68, 68)"
                  _hover={{
                    bg: "rgba(239, 68, 68, 0.05)",
                    borderColor: "rgb(220, 38, 38)",
                    color: "rgb(220, 38, 38)",
                  }}
                  _active={{
                    bg: "rgba(239, 68, 68, 0.1)",
                  }}
                  borderRadius="12px"
                  h="48px"
                  fontWeight="500"
                  transition="all 0.2s"
                >
                  {t("784")}
                </Button>
              </Box>
            </Stack>
          </InfoCard>
        </MotionBox>

        {/* 关于卡片 */}
        <MotionBox
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, delay: 0.3 }}
        >
          <InfoCard
            icon={
              <svg
                width="24"
                height="24"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
              >
                <circle cx="12" cy="12" r="10" />
                <line x1="12" y1="16" x2="12" y2="12" />
                <line x1="12" y1="8" x2="12.01" y2="8" />
              </svg>
            }
            title={t("750")}
          >
            <VStack spacing={2} textAlign="center">
              <Text color={textColor} fontSize="md">
                {t("752")}
              </Text>
              <Text color="rgb(156, 163, 175)" fontSize="sm">
                {t("753")}
              </Text>
            </VStack>
          </InfoCard>
        </MotionBox>
      </Stack>

      {/* 恢复出厂设置确认对话框 */}
      <AlertDialog
        isOpen={showResetDialog}
        leastDestructiveRef={cancelRef}
        onClose={() => setShowResetDialog(false)}
      >
        <AlertDialogOverlay
          bg="rgba(0, 0, 0, 0.4)"
          backdropFilter="blur(8px)"
        />
        <AlertDialogContent
          bg="rgba(255, 255, 255, 0.95)"
          backdropFilter="blur(20px)"
          borderRadius="16px"
          border="1px solid rgba(0, 0, 0, 0.1)"
          boxShadow="0 8px 32px rgba(0, 0, 0, 0.1)"
          style={{
            WebkitBackdropFilter: "blur(20px)",
          }}
        >
          <AlertDialogHeader
            fontSize="lg"
            fontWeight="600"
            color="rgb(15, 23, 42)"
          >
            {t("784")}
          </AlertDialogHeader>

          <AlertDialogBody color="rgb(100, 116, 139)">
            {t("785")}
          </AlertDialogBody>

          <AlertDialogFooter gap={3}>
            <Button
              ref={cancelRef}
              onClick={() => setShowResetDialog(false)}
              variant="outline"
              borderColor="rgb(226, 232, 240)"
              color="rgb(100, 116, 139)"
              _hover={{
                bg: "rgba(0, 0, 0, 0.05)",
                borderColor: "rgb(203, 213, 225)",
              }}
              borderRadius="8px"
            >
              {t("786")}
            </Button>
            <Button
              onClick={handleResetDevice}
              bg="rgb(239, 68, 68)"
              color="white"
              _hover={{
                bg: "rgb(220, 38, 38)",
              }}
              _active={{
                bg: "rgb(185, 28, 28)",
              }}
              borderRadius="8px"
            >
              {t("787")}
            </Button>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 升级固件对话框 */}
      <AlertDialog
        isOpen={showUpgradeDialog}
        leastDestructiveRef={cancelRef}
        onClose={() => !isUpgrading && setShowUpgradeDialog(false)}
      >
        <AlertDialogOverlay
          bg="rgba(0, 0, 0, 0.4)"
          backdropFilter="blur(8px)"
        />
        <AlertDialogContent
          bg="rgba(255, 255, 255, 0.95)"
          backdropFilter="blur(20px)"
          borderRadius="16px"
          border="1px solid rgba(0, 0, 0, 0.1)"
          boxShadow="0 8px 32px rgba(0, 0, 0, 0.1)"
          style={{
            WebkitBackdropFilter: "blur(20px)",
          }}
        >
          <AlertDialogHeader
            fontSize="lg"
            fontWeight="600"
            color="rgb(15, 23, 42)"
          >
            {t("782")}
          </AlertDialogHeader>

          <AlertDialogBody>
            {!isUpgrading ? (
              <Text color="rgb(100, 116, 139)">{t("788")}</Text>
            ) : (
              <VStack spacing={4}>
                <Text
                  color="rgb(15, 23, 42)"
                  fontWeight="500"
                  textAlign="center"
                >
                  {t("789")}
                </Text>
                <Box w="100%">
                  <Progress
                    value={upgradeProgress}
                    size="md"
                    bg="rgba(255, 140, 0, 0.1)"
                    sx={{
                      "& > div": {
                        background:
                          "linear-gradient(90deg, rgb(255, 140, 0) 0%, rgb(255, 120, 0) 100%)",
                        boxShadow: "0 0 8px rgba(255, 140, 0, 0.3)",
                      },
                    }}
                    borderRadius="full"
                  />
                  <Text
                    color="rgb(100, 116, 139)"
                    fontSize="sm"
                    textAlign="right"
                    mt={2}
                  >
                    {Math.round(upgradeProgress)}%
                  </Text>
                </Box>
              </VStack>
            )}
          </AlertDialogBody>

          <AlertDialogFooter gap={3}>
            {!isUpgrading && (
              <>
                <Button
                  ref={cancelRef}
                  onClick={() => setShowUpgradeDialog(false)}
                  variant="outline"
                  borderColor="rgb(226, 232, 240)"
                  color="rgb(100, 116, 139)"
                  _hover={{
                    bg: "rgba(0, 0, 0, 0.05)",
                    borderColor: "rgb(203, 213, 225)",
                  }}
                  borderRadius="8px"
                >
                  {t("790")}
                </Button>
                <Button
                  onClick={handleUpgradeFirmware}
                  bg={`linear-gradient(135deg, ${accentColor} 0%, ${accentColor} 100%)`}
                  color="white"
                  _hover={{
                    background:
                      "linear-gradient(135deg, rgb(255, 120, 0) 0%, rgb(255, 145, 0) 100%)",
                    transform: "translateY(-1px)",
                    boxShadow: "0 6px 16px rgba(255, 140, 0, 0.4)",
                  }}
                  _active={{
                    bg: "rgb(29, 78, 216)",
                  }}
                  borderRadius="8px"
                  display="none"
                >
                  {t("791")}
                </Button>
              </>
            )}
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </Box>
  );
}

export default KBDeviceInfo;
